<template>
  <view class="section">
    <view class="content">
      <view class="box">
        <template v-if="isShowRequirement">
          <view class="introduction">
            {{ taskInfo.promptContent }}
          </view>
        </template>
        <template v-else>
          <view class="subject">
            <view
              class="subject_content"
              v-for="(item, index) in questionList"
              optionAnswer
              :key="index"
            >
              <text>{{ item.optionAnswer }}</text>
            </view>
          </view>
        </template>
      </view>
    </view>
    <view class="operation">
      <view class="operation_content" v-if="answerStatus !== '3'">
        <view class="operation_progress">
          <u-circle-progress
            active-color="#2979ff"
            :percent="percent"
            width="104"
            border-width="4"
            bg-color="#e0e9f9"
            inactive-color="#e0e9f9"
          >
            <view class="operation_progress_content" @click="start()">
              <image
                v-show="playStatus"
                src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/suspend.png"
                mode="widthFix"
                style="width: 28rpx"
              ></image>
              <image
                v-show="!playStatus"
                src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/play.png"
                mode="widthFix"
                style="width: 30rpx"
              ></image>
            </view>
          </u-circle-progress>
        </view>
      </view>
      <view class="operation_content" v-else>
        <view class="operation_progress">
          <u-circle-progress
            active-color="#2979ff"
            :percent="recordPercent"
            width="104"
            border-width="4"
            bg-color="#e0e9f9"
            inactive-color="#e0e9f9"
          >
            <view class="operation_progress_content" @click="endRecord()">
              <image
                src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/app/voice.png"
                mode="widthFix"
                style="width: 36rpx"
              ></image>
            </view>
          </u-circle-progress>
        </view>
        <text>点击结束</text>
      </view>
      <view class="operation_text">
        <template v-if="isShowRequirement">
          <text>答题要求播放中{{ countDown | timeFilter }}</text>
        </template>
        <template v-else>
          <text v-if="answerStatus === '1'"
            >请阅读相关题目{{ tipsTime | timeFilter }}</text
          >
          <text v-else-if="answerStatus === '2'"
            >答题要求播放中{{ countDown | timeFilter }}</text
          >
          <text v-else-if="answerStatus === '3'"
            >录音中{{ answerTime | timeFilter }}</text
          >
        </template>
      </view>
      <template v-if="type === '0'">
        <view
          class="operation_button"
          @click="skip()"
          v-if="answerStatus !== '3'"
        >
          <text>跳过</text>
        </view>
      </template>
      <template v-else>
        <view class="operation_noop"> </view>
      </template>
    </view>
  </view>
</template>
<script>
import permision from "@/js_sdk/wa-permission/permission.js";
import parser from "fast-xml-parser";

const recorderManager = uni.getRecorderManager();
const innerAudioContext = uni.createInnerAudioContext();

innerAudioContext.autoplay = true;
export default {
  components: {},
  props: {
    type: {
      type: String,
      default: "0",
    },
    taskInfo: {
      type: Object,
      default: null,
    },
    questionInfo: {
      type: Object,
      default: null,
    },
    questionList: {
      type: Array,
      default: () => [],
    },
    doneCount: {
      type: Number,
      default: 0,
    },
    questionCount: {
      type: Number,
      default: 0,
    },
  },
  watch: {
    questionInfo() {
      this.initData();
      this.init();
    },
  },
  computed: {
    percent() {
      if (this.duration > 0) {
        return parseInt((this.currentTime / this.duration) * 100);
      }
    },
    recordPercent() {
      return parseInt(100 - (this.answerTime / this.recordTime) * 100);
    },
    countDown() {
      return parseInt(this.duration - this.currentTime);
    },
    questionItem() {
      return this.questionList[this.currentIndex];
    },
  },
  filters: {
    timeFilter(value) {
      let minute =
        Math.floor(value / 60) >= 10
          ? Math.floor(value / 60)
          : "0" + Math.floor(value / 60);
      value -= 60 * minute;
      let second = value >= 10 ? value : "0" + value;
      return minute + ":" + second;
    },
  },
  data() {
    return {
      answerStatus: "1",
      isShowRequirement: true,
      listenNumber: 1,
      frequency: 1,
      tipsTime: 0,
      answerTime: 0,
      recordTime: 0,
      timerId: null,
      audio: null,
      currentIndex: 0,
      currentTime: 0,
      duration: 0,
      playStatus: false,
      isCanSkip: true,
      score: 0,
      total_score: 0,
      fluency_score: 0,
      integrity_score: 0,
      answers: [],
      isCanClick: true,
      isIos: true,
      voicePath: "",
      recordOptions: {
        duration: 60000,
        sampleRate: 16000,
        encodeBitRate: 48000,
      },
      permisionIosMap: {
        location: "位置",
        camera: "摄像头",
        photoLibrary: "相册",
        record: "麦克风",
        push: "推送",
        contact: "通讯录",
        calendar: "日历",
        memo: "备忘录",
      },
      permisionAndroidMap: {
        "android.permission.ACCESS_FINE_LOCATION": "位置",
        "android.permission.ACCESS_COARSE_LOCATION": "模糊位置",
        "android.permission.CAMERA": "摄像头",
        "android.permission.READ_EXTERNAL_STORAGE": "外部存储(含相册)读取",
        "android.permission.WRITE_EXTERNAL_STORAGE": "外部存储(含相册)写入",
        "android.permission.RECORD_AUDIO": "麦克风",
        "android.permission.READ_CONTACTS": "通讯录读取",
        "android.permission.WRITE_CONTACTS": "通讯录写入",
        "android.permission.READ_CALENDAR": "日历读取",
        "android.permission.WRITE_CALENDAR": "日历写入",
        "android.permission.READ_SMS": "短信读取",
        "android.permission.SEND_SMS": "短信发送",
        "android.permission.RECEIVE_SMS": "接收新短信",
        "android.permission.READ_PHONE_STATE": "获取手机识别码等信息的",
        "android.permission.CALL_PHONE": "拨打电话",
        "android.permission.READ_CALL_LOG": "获取通话记录",
      },
    };
  },
  created() {
    // #ifdef APP-PLUS
    this.isIos = plus.os.name == "iOS";
    // #endif
    let self = this;
    recorderManager.onStop(function (res) {
      self.voicePath = res.tempFilePath;
      self.uploadVoice();
    });
    this.init();
  },
  methods: {
    init() {
      this.initQuestionList();
      this.initAudio();
      this.initInfo();
    },
    initQuestionList() {
      this.questionList.forEach((item) => {
        this.$set(item, "choiceAnswer", "");
      });
    },
    initInfo() {
      this.frequency = this.taskInfo.frequency;
      this.tipsTime = this.questionInfo.tipTime;
      this.answerTime = this.questionInfo.prepareTime;
      this.recordTime = this.questionInfo.prepareTime;
    },
    initData() {
      this.answerStatus = "1";
      this.listenNumber = 1;
      this.playStatus = false;
      this.initAudio();
      this.initInfo();
    },
    initAudio() {
      let audioUrl = "";
      if (this.isShowRequirement) {
        audioUrl = this.taskInfo.promptAudio;
      } else {
        if (this.answerStatus === "1") {
          this.tipsTimer();
          return;
        } else if (this.answerStatus === "2") {
          audioUrl = this.questionInfo.audioUrl;
        } else if (this.answerStatus === "3") {
          this.answerTimer();
          return;
        }
      }
      this.audio = uni.createInnerAudioContext();
      this.audio.src = audioUrl;
      this.onTimeUpdate();
      this.onCanplay();
      this.onEnded();
      this.start();
      uni.$on("stop", () => {
        this.audio.stop();
        this.playStatus = false;
      });
    },
    start() {
      if (!this.isShowRequirement) {
        if (this.answerStatus === "1" || this.answerStatus === "3") return;
      }
      //点击播放
      if (this.playStatus) {
        this.audio.pause();
        this.playStatus = !this.playStatus;
      } else {
        this.audio.play();
        this.playStatus = !this.playStatus;
      }
    },
    pause() {
      uni.$emit("stop");
    },
    onCanplay() {
      //进入可播放状态
      this.audio.onCanplay(() => {
        this.audio.duration;
        setTimeout(() => {
          this.duration = this.audio.duration;
        }, 1000);
      });
    },
    onTimeUpdate() {
      //音频播放进度
      this.audio.onTimeUpdate(() => {
        if (!Number.isFinite(this.audio.duration)) {
          this.audio.currentTime = Number.MAX_SAFE_INTEGER;
          this.audio.currentTime = 0;
        } else {
          this.duration = this.audio.duration;
          this.currentTime = this.audio.currentTime;
        }
      });
    },
    onEnded() {
      //播放结束
      this.audio.onEnded(() => {
        this.skip();
      });
    },
    tipsTimer() {
      this.timerId = setInterval(() => {
        if (this.tipsTime > 0) {
          this.tipsTime--;
        } else {
          clearInterval(this.timerId);
          this.skip();
        }
      }, 1000);
    },
    answerTimer() {
      this.timerId = setInterval(() => {
        if (this.answerTime > 0) {
          this.answerTime--;
        } else {
          this.endRecord();
        }
      }, 1000);
      this.record();
    },
    skip() {
      if (!this.isCanSkip) return;
      this.isCanSkip = false;
      setTimeout(() => {
        this.isCanSkip = true;
      }, 1000);
      uni.$emit("stop");
      if (this.isShowRequirement) {
        this.isShowRequirement = !this.isShowRequirement;
      } else {
        if (this.answerStatus === "1") {
          this.answerStatus = "2";
        } else if (this.answerStatus === "2") {
          if (this.timerId) clearInterval(this.timerId);
          this.answerStatus = "3";
        }
      }
      this.initAudio();
    },
    testSubmit() {
      let list = [];
      this.questionList.forEach((item) => {
        list.push({
          itemId: item.id,
          userAnswer: item.choiceAnswer,
          score: item.choiceAnswer === item.optionAnswer ? item.score : 0,
        });
      });
      this.$emit("submit", list);
    },
    record() {
      if (!this.isCanClick) return;
      this.isCanClick = false;
      setTimeout(() => {
        this.isCanClick = true;
      }, 1000);
      if (this.isIos) {
        this.judgeIosPermission("record");
      } else {
        this.requestAndroidPermission("android.permission.RECORD_AUDIO");
      }
    },
    judgeIosPermission: function (permisionID) {
      var result = permision.judgeIosPermission(permisionID);
      var strStatus = result ? "已" : "未";
      if (!result) {
        uni.showModal({
          title: "",
          content:
            this.permisionIosMap[permisionID] +
            "权限" +
            strStatus +
            "获得授权,是否去开启？",
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              plus.runtime.openURL("app-settings://");
            }
          },
        });
      } else {
        this.startRecord();
      }
    },
    async requestAndroidPermission(permisionID) {
      var result = await permision.requestAndroidPermission(permisionID);
      var strStatus;
      if (result == 1) {
        strStatus = "已获得授权";
        this.startRecord();
      } else if (result == 0) {
        strStatus = "未获得授权";
      } else {
        strStatus = "被永久拒绝权限";
        uni.showModal({
          title: "",
          content: this.permisionAndroidMap[permisionID] + "权限" + strStatus,
          showCancel: false,
        });
      }
    },
    startRecord() {
      recorderManager.start(this.recordOptions);
    },
    endRecord() {
      clearInterval(this.timerId);
      recorderManager.stop();
    },
    playVoice() {
      if (this.voicePath) {
        innerAudioContext.src = this.voicePath;
        innerAudioContext.play();
      }
    },
    uploadVoice() {
      this.$upload(this.voicePath, {
        wordText: this.questionInfo.audioContent,
      }).then((res) => {
        let xml = res.data;
        let grade = parser.parse(xml, {
          attributeNamePrefix: "",
          ignoreAttributes: false,
        });
        if (grade) {
          let read_chapter =
            grade.xml_result.read_sentence.rec_paper.read_chapter;
          this.total_score = parseInt(read_chapter.total_score);
          this.fluency_score = parseInt(read_chapter.fluency_score);
          this.integrity_score = parseInt(read_chapter.integrity_score);
          this.score = Math.round(
            (this.total_score / 100) * this.questionItem.score
          );
          this.$upload(
            this.voicePath,
            {
              title: "听说考试录音",
            },
            "/admin/sysAttachment/uploadTemp"
          ).then((res) => {
            this.answers.push({
              itemId: this.questionItem.id,
              userAnswer: res.data,
              totalScore: this.total_score,
              completeScore: this.integrity_score,
              fluencyScore: this.fluency_score,
            });
            this.handleResult();
          });
        }
      });
    },
    handleResult() {
      if (this.currentIndex === this.questionList.length - 1) {
        this.$emit("submit", this.answers);
        return;
      }
      this.currentIndex++;
      this.initData();
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./ReadingAloud.scss";
</style>
